import os

from django.db import models
from django.contrib.auth.models import AbstractUser, Group
from django.templatetags.static import static
from django.conf import settings
from django.core.exceptions import ValidationError
from colorful.fields import RGBColorField


default_color = '#000000'
default_font_color = '#ffffff'


class Level(models.Model):
    value = models.IntegerField(primary_key=True, verbose_name='数值')
    color = RGBColorField(default=default_color, verbose_name='颜色')
    # font_color = RGBColorField(default=default_font_color, verbose_name='字体颜色')

    def __str__(self):
        return f'第{self.value}级'

    class Meta:
        verbose_name = '等级'
        verbose_name_plural = '等级'
        ordering = ('-value', )


class Identity(models.Model):
    level = models.ForeignKey(Level, on_delete=models.CASCADE, verbose_name='等级')
    name = models.CharField(primary_key=True, max_length=100, verbose_name='名称')

    def __str__(self):
        return f'第{self.level.value}级：{self.name}'

    class Meta:
        verbose_name = '身份'
        verbose_name_plural = '身份'
        ordering = ('-level',)


images = [
    'image',
    'background',
]


def get_path(instance, tp):
    user_path = os.path.join('UserImages', str(instance.id))
    abs_user_path = os.path.join(settings.MEDIA_ROOT, user_path)
    if os.path.exists(abs_user_path):
        for file in os.listdir(abs_user_path):
            file_path = os.path.join(abs_user_path, file)
            filename_without_ext = os.path.splitext(file)[0]
            if filename_without_ext not in images or filename_without_ext == tp:
                try:
                    os.remove(file_path)
                except BaseException:
                    pass
    return user_path


def upload_to(instance, filename, tp):
    path = os.path.join(get_path(instance, tp), f'{tp}{os.path.splitext(filename)[-1]}')
    return path


def upload_to_image(instance, filename):
    return upload_to(instance, filename, 'image')


def upload_to_background(instance, filename):
    return upload_to(instance, filename, 'background')


def validate_image_size(value):
    if value.size > 1 * 1024 * 1024:  # 最大限制为1MB
        raise ValidationError("Image file is too large (max 1 MB) !")


class CustomUser(AbstractUser):
    identity = models.ForeignKey(Identity, on_delete=models.SET_NULL, verbose_name='身份',
                                 null=True, blank=True)
    image = models.ImageField(upload_to=upload_to_image, null=True, verbose_name='头像',
                              validators=[validate_image_size,])
    background = models.ImageField(upload_to=upload_to_background, null=True, verbose_name='聊天背景',
                                   validators=[validate_image_size,])
    homepage = models.TextField(max_length=100000, verbose_name='主页',
                                default='这是一位正在为老教的发展而奋斗的教徒，无暇在此留下笔墨。')

    def get_badge_display(self):
        value = self.identity.level.value if self.identity else -1
        color = '#000000' if self.identity is None or settings.LOW else self.identity.level.color
        name = self.identity.name if self.identity else '用户'
        return (f'<span class="badge" style="background-color: {color};'
                f'{" font-family: HYQingZhouXingJ;" if value >= 0 else ""}">'
                f'{name}'
                f'</span>')

    def get_username_display(self):
        value = self.identity.level.value if self.identity else -1
        color = '#000000' if self.identity is None or settings.LOW else self.identity.level.color
        name = self.username
        return (f'<span style="color: {color};'
                f'{" font-family: HYQingZhouXingJ;" if value >= 0 else ""}">'
                f'{name}'
                f'</span>')

    def get_username_display_without_color(self):
        value = self.identity.level.value if self.identity else -1
        name = self.username
        return (f'<span style="'
                f'{"font-family: HYQingZhouXingJ;" if value >= 0 else ""}">'
                f'{name}'
                f'</span>')

    def get_display(self):
        return self.get_badge_display() + '&nbsp;' + self.get_username_display()

    def get_image_url(self):
        return self.image.url if self.image else static('img/favicon.jpg')

    def get_background_url(self):
        return self.background.url if self.background else static('chat/img/background.jpg')

    class Meta:
        ordering = ('-identity', '-is_staff', '-is_superuser', '-username')
        verbose_name = '用户'
        verbose_name_plural = '用户'
